package com.mccree.server;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;

public class GroupChatServer {
    //定义属性
    private Selector selector;
    private ServerSocketChannel listenChannel;

    private static final int PORT = 6667;

    //初始化工作
    public GroupChatServer(){
        try {
            selector = Selector.open();
            listenChannel = ServerSocketChannel.open();
            listenChannel.socket().bind(new InetSocketAddress(PORT));
            //设置非阻塞模式
            listenChannel.configureBlocking(false);
            //将listenChannel注册到selector
            listenChannel.register(selector, SelectionKey.OP_ACCEPT);
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        GroupChatServer groupChatServer = new GroupChatServer();
        groupChatServer.listen();
    }

    public void listen(){
        try {
            while (true){
                int count = selector.select();
                //有事件处理
                if (count>0){
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()){
                        SelectionKey key = iterator.next();
                        //监听处理
                        if (key.isAcceptable()){
                            SocketChannel socketChannel = listenChannel.accept();
                            socketChannel.configureBlocking(false);
                            //注册
                            socketChannel.register(selector,SelectionKey.OP_READ);
                            //提示
                            System.out.println(socketChannel.getRemoteAddress()+"上线");
                        }
                        //通道发送read事件
                        if (key.isReadable()){
                            readData(key);
                        }
                        //删除key，防止重复处理
                        iterator.remove();
                    }
                }else {
                    System.out.println("等待.....");
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //发生异常的处理
        }
    }
    //读取客户端消息
    public void readData(SelectionKey key){
        SocketChannel socketChannel = null;
        try {
           socketChannel = ((SocketChannel) key.channel());
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            int count = socketChannel.read(byteBuffer);
            if (count>0){
                String msg = new String(byteBuffer.array());
                System.out.println("form客户端:"+msg);
                //向其他客户端转发消息
                sendInfoOtherClients(msg,socketChannel);
            }
        }catch (IOException e){
            try {
                System.out.println(socketChannel.getRemoteAddress()+"离线了");
                //取消注册
                key.cancel();
                //关闭通道
                socketChannel.close();
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }
    //转发消息给其他客户端(Channel)
    private void sendInfoOtherClients(String msg,SocketChannel socketChannel) throws IOException{
        System.out.println("服务器转发消息中....");
        //便利所有selector上的socketchannel并排除转发者
        for (SelectionKey key : selector.keys()) {
            Channel targetChannel = key.channel();
            //排除自己并将消息写入目标管道
            if (targetChannel instanceof SocketChannel && targetChannel != socketChannel){
                SocketChannel destChannel = (SocketChannel) targetChannel;
                ByteBuffer byteBuffer = ByteBuffer.wrap(msg.getBytes());
                destChannel.write(byteBuffer);
            }
        }
        System.out.println("服务器转发完成");
    }

}
